package cos

import (
	"bgs/conf"
	"context"
	"fmt"
	"io"
	"net/http"
	"net/url"
	"github.com/tencentyun/cos-go-sdk-v5"
	"github.com/tencentyun/cos-go-sdk-v5/debug"
)

type Cos struct {
	cosConfPtr *conf.CosSection
	BucketUrl  *cos.BaseURL
}

// NewCos new cos client
func NewCos(cosConfPtr *conf.CosSection) *Cos {
	u, _ := url.Parse(cosConfPtr.BgpBucketURI)
	b := &cos.BaseURL{BucketURL: u}
	s := &Cos{
		cosConfPtr: cosConfPtr,
		BucketUrl:  b,
	}
	return s
}

// Upload 上传cos
func (s *Cos) Upload(ctx context.Context, reader io.Reader, name string) (link string, err error) {

	c := cos.NewClient(s.BucketUrl, &http.Client{
		Transport: &cos.AuthorizationTransport{
			// 通过环境变量获取密钥
			// 环境变量 COS_SECRETID 表示用户的 SecretId，登录访问管理控制台查看密钥，https://console.cloud.tencent.com/cam/capi
			SecretID: s.cosConfPtr.SecretID,
			// 环境变量 COS_SECRETKEY 表示用户的 SecretKey，登录访问管理控制台查看密钥，https://console.cloud.tencent.com/cam/capi
			SecretKey: s.cosConfPtr.SecretKey,
			// Debug 模式，把对应 请求头部、请求内容、响应头部、响应内容 输出到标准输出
			Transport: &debug.DebugRequestTransport{
				RequestHeader: true,
				// Notice when put a large file and set need the request body, might happend out of memory error.
				RequestBody:    false,
				ResponseHeader: true,
				ResponseBody:   false,
			},
		},
	})

	// Case1 上传对象
	_, err = c.Object.Put(context.Background(), name, reader, nil)
	if err != nil {
		return
	}
	link = fmt.Sprintf("%s/%s", s.cosConfPtr.BgpURI, url.QueryEscape(name))
	return link, nil
}
